package org.softmed.rest.editor.commons;

import java.awt.Color;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.softmed.filehandling.FileUtil;

public class AddressBar extends JPanel implements URIProvider {
	String lastURI = "http://localhost:8090";
	FileUtil util = new FileUtil();
	JTextField uri = new JTextField();
	String uriFileName = "last-uri.txt";

	public AddressBar() {
		// setBackground(Color.YELLOW);
		setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
		add(new JLabel("URI:"));
		add(uri);

		SwingUtil.setSize(uri, 230, 20);

		readURI();

		SwingUtil.setSize(this, 250, 20);

	}

	protected void readURI() {

		File file = util.getFile(uriFileName);
		if (file.exists()) {
			try {
				String temp = util.readFromFile(file);
				if (temp != null && temp.length() > 0)
					lastURI = temp;

				setURIToTextField();
			} catch (Throwable t) {
				setURIToTextField();
			}
		} else
			setURIToTextField();

	}

	protected void setURIToTextField() {
		lastURI = lastURI.replaceAll("\\s*", "");
		uri.setText(lastURI);
	}

	public void writeLastURI() throws Throwable {
		util.saveToFile(uriFileName, getURI());
	}

	public String getURI() {
		return uri.getText();
	}

	public void setURI(String uri) {
		this.uri.setText(uri);
	}

	public JTextField getUriField() {
		return uri;
	}

}
